#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
import urllib
import webapp2
import jinja2
import json
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.api import files
JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)


class Message(db.Model):
  sendUser = db.StringProperty()
  recvUser = db.StringProperty()
  content = db.StringProperty()
  time = db. DateTimeProperty(auto_now_add = True)
  read = db.BooleanProperty() 


class UserOnline(db.Model):
  user_id = db.StringProperty();
  online = db.BooleanProperty();
  nickname = db.StringProperty();
  def to_dict(self):
       return dict([(p, unicode(getattr(self, p))) for p in self.properties()])



class MainHandler(webapp2.RequestHandler):
  def get(self):        
    user = users.get_current_user()
    if user:
      user_db = UserOnline.get_or_insert(user.email(),user_id= user.user_id(),online = True,nickname = user.nickname())     
      template = JINJA_ENVIRONMENT.get_template('index.html')
      self.response.write(template.render())
    else:
      self.redirect(users.create_login_url(self.request.uri))



def gql_json_parser(query_obj):
    result = []
    for entry in query_obj:
        result.append(dict([(p, unicode(getattr(entry, p))) for p in entry.properties()]))
    return result

class ChatHandler(webapp2.RequestHandler):
    def post(self):      
      user = users.get_current_user()

class UserHandler(webapp2.RequestHandler):
    def get(self):      
      self.response.headers['Content-Type'] = 'application/json'   
      users_db  = UserOnline.all().filter('online =', True) + UserOnline.all()
      self.response.out.write(json.dumps(gql_json_parser(users_db)))

class ChatHandler(webapp2.RequestHandler):
  def post(self):
    user = users.get_current_user()
    if user:  
      email = self.request.get("email")
      if email:
        refUser = UserOnline.get(user_id= user.user_id())   
        if refUser:
          friend = Friend(user = user.user_id(), ref_user = refUser.user_id())
          friend.put()
    else:
      self.redirect(users.create_login_url(self.request.uri))

# class UserHandler
app = webapp2.WSGIApplication([
    ('/', MainHandler),
    ('/Chat', ChatHandler),
    ('/User', UserHandler)
], debug=True)
